<template>
  <div>
    <el-form ref="userForm" :model="user" label-width="80px" label-position="left" :rules="formRules">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="user.username" type="text" placeholder="请输入用户名"/>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="user.password" type="password" placeholder="请输入密码"/>
      </el-form-item>
      <el-form-item >
        <el-button type="primary" @click="submitForm">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  export default {
    name: "Select",
    data(){
      //第二个参数文本框中的值，第三个参数是验证后要调用的函数，这个函数时系统传递给我们的
      let checkEmail=(rule,value,callback)=>{
        if(/^\w+@\w+\.com$/.test(value)){
          callback();//满足的情况
        }else{
          callback(new Error("用户名必须是一个邮箱"))
        }
      }
      return {
        user:{
          username:"",
          password:""
        },
        formRules:{
          username:[
            {required:true,message:"用户名必须填写",trigger:"blur"},
            {min:3,max:50,message: "长度在3~50个字符",trigger: "blur"},
            {validator:checkEmail,trigger: "blur"}
            ],
          password:[{required:true,message:"密码不能为空",trigger:"blur"}]
        }
      }
    },
    methods:{
      submitForm(){
        //valid就是form表单是否验证通过。true表示验证通过，false验证不通过。
        this.$refs["userForm"].validate((valid)=>{
          if(valid){
            alert("验证通过")
          }else{
            alert("验证不通过");
          }
          return valid;
        });
      }
    }
  }
</script>
